<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 400px;
        height: 200px;
        border: 10px solid pink;
        margin: 50px 100px;
        padding: 20px;
      }
      span {
        position: fixed;
        border: 1px solid #000;
        padding: 5px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="box">box</div>
    <span>回到顶部</span>
    <div style="height: 1000px"></div>
  </body>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
  <script>
    $(function () {  //回调函数 加不加都可以
      //实例：回到顶端
      //当向下滚到距离top：100px时出现“回到顶部”
      var topShow = function () {
        //封装为一个函数
        var top = Math.round($(document).scrollTop());
        if (top >= 100) {
          //$("span").css("display", "block");
          $("span").fadeIn(400);
        } else {
          $("span").css("display", "none");
          //$("span").fadeOut(400);
        }
      };
      topShow();
      $(window).scroll(function () {
        //滚动时调用toShow函数
        topShow();
      });

      //单击“回到顶部”可以回到顶部
      $("span").click(function () {
        $(document).scrollTop(0);
      });
      //$(document).scrollLeft()
    });
  </script>
</html>
